package com.xy.novelweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.xy.novelweb.domain.Reader;
import com.xy.novelweb.service.alipay.AlipayService;
import com.xy.novelweb.utils.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 支付宝
 * @author lcc
 * @data :2018年6月4日 上午10:55:46
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class AlipayController {

		@Autowired
		@Qualifier("alipayService")
		private AlipayService alipayService;

		@RequestMapping("/pay")
		public void payment(HttpServletResponse response, HttpServletRequest request) {
				try {
						alipayService.aliPay(response,request);
				} catch (IOException e) {
						e.printStackTrace();
				}
		}
		/**
		 * web 订单支付
		 */
		@GetMapping("getPagePay")
		public Object getPagePay() throws Exception{
				/** 模仿数据库，从后台调数据*/
				String outTradeNo = UUID.randomUUID().toString();
				Integer totalAmount = 11;
				String subject = "228";

				String pay = alipayService.webPagePay(outTradeNo, totalAmount, subject);
				log.info(pay);

				Map<Object, Object> pays = new HashMap<>();
				pays.put("pay", pay);

				return pay;
		}

		/**
		 * app 订单支付
		 */
		@GetMapping("getAppPagePay")
		public Object getAppPagePay() throws Exception{
				/** 模仿数据库，从后台调数据*/
				String outTradeNo = "131233";
				Integer totalAmount = 1000;
				String subject = "天猫超市012";

				String pay = alipayService.appPagePay(outTradeNo, totalAmount, subject);

				Object json = JSONObject.toJSON(pay);

				log.info(json+"");

				return json;
		}

		/**
		 * 交易查询
		 */
		@PostMapping("aipayQuery")
		public Object alipayQuery() throws Exception{
				/**调取支付订单号*/
				String outTradeNo = "13123";

				String query = alipayService.query(outTradeNo);

				Object json = JSONObject.toJSON(query);

        /*JSONObject jObject = new JSONObject();
        jObject.get(query);*/
				return json;
		}

		/**
		 * 退款
		 * @throws AlipayApiException
		 */
		@GetMapping("alipayRefund")
		public Object alipayRefund(
			@RequestParam("outTradeNo")String outTradeNo,
			@RequestParam(value = "outRequestNo", required = false)String outRequestNo,
			@RequestParam(value = "refundAmount", required = false)Integer refundAmount
		) throws AlipayApiException{

				/** 调取数据*/
				//String outTradeNo = "15382028806591197";
				String refundReason = "用户不想购买";
				//refundAmount = 1;
				//outRequestNo = "22";

				String refund = alipayService.refund(outTradeNo, refundReason, refundAmount, outRequestNo);

				log.info(refund);

				return refund;
		}

		/**
		 * 退款查询
		 * @throws AlipayApiException
		 */
		@PostMapping("refundQuery")
		public Object refundQuery() throws AlipayApiException{

				/** 调取数据*/
				String outTradeNo = "13123";
				String outRequestNo = "2";

				String refund = alipayService.refundQuery(outTradeNo, outRequestNo);

				return refund;

		}

		/**
		 * 交易关闭
		 * @throws AlipayApiException
		 */
		@PostMapping("alipayclose")
		public Object alipaycolse() throws AlipayApiException {

				/** 调取数据*/
				String outTradeNo = "13123";

				String close = alipayService.close(outTradeNo);

				return close;
		}

		@RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
		@ResponseBody
		public String goAlipay(HttpServletRequest request, HttpServletRequest response,String price,String describe) throws Exception {


				/** 调取支付宝接口app端支付*/
				AlipayClient alipayClients = new DefaultAlipayClient(
					AlipayConfig.GATEWAYURL, AlipayConfig.APP_ID, AlipayConfig.MERCHANT_PRIVATE_KEY, "json", AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);
				log.info("price="+price);
				log.info("request  price="+request.getParameter("price"));
				log.info("describe="+describe);
				//设置请求参数
				AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
				alipayRequest.setReturnUrl(AlipayConfig.return_url);
				alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

				Reader reader = (Reader) request.getSession().getAttribute("user_reader");

				//商户订单号，商户网站订单系统中唯一订单号，必填
				String out_trade_no = UUID.randomUUID().toString();
				//付款金额，必填
				String total_amount = price;
				//订单名称，必填
				String subject = "201609300062792277";
				//商品描述，可空
				String body = describe;
				//买家id
				String buyer_id = reader.getNickName();
				// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。
				String timeout_express = "1c";

				alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
					+ "\"total_amount\":\""+ total_amount +"\","
					+ "\"subject\":\""+ subject +"\","
					+ "\"body\":\""+ body +"\","
					+ "\"buyer_id\":\""+ buyer_id +"\","
					+ "\"timeout_express\":\""+ timeout_express +"\","
					+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

				//请求
				String result = alipayClients.pageExecute(alipayRequest).getBody();
				log.info("请求 = "+result);
				return result;
		}

}


